【SwiftUI】大きいプログレスバーを表示したい

【SwiftUI】大きいプログレスバーを表示したい

Clock Icon2024.07.16

通常のSwiftUIで用意されているプログレスバーが自分の欲しいサイズに比べると小さかった為、大きいプログレスバーの表示方法を調べました。

環境

  • Xcode 15.2

通常

struct ProgressBarView: View {
    var body: some View {
        ProgressView(value: 20, total: 100)
            .tint(.red)
            .padding()
    }
}

すごい小さいです。

しかし、下記のようにheightを与えても高さが変わりません。

struct ProgressBarView: View {
    var body: some View {
        ProgressView(value: 20, total: 100)
            .frame(height: 100)
            .tint(.red)
            .padding()
    }
}

scaleEffectで拡大

今回は縦方向のサイズを変更したいので、y方向のscaleEffectの値を4倍にしてみます。

struct ProgressBarView: View {
    var body: some View {
        ProgressView(value: 20, total: 100)
            // y方向の倍率を変更
            .scaleEffect(x: 1, y: 4, anchor: .center)
            .tint(.red)
            .padding()
    }
}

高さが変更されました。

しかし、よく見ると、プログレスバーが四角っぽくなってしまいました。

先端が丸くなるようにクリップする

clipShapeを付与した後に、heightの値やscaleEffectyの値をお好みで指定しながら、理想な形になるように調整してみてください

struct ProgressBarTestView: View {
    var body: some View {
        ProgressView(value: 20, total: 100)
            .tint(.red)
            .frame(height: 20)
            .scaleEffect(x: 1, y: 40, anchor: .center)
            // カプセル形状にクリップする
            .clipShape(Capsule())
            .padding()
    }
}

おまけ

大きいプログレスバー用にProgressViewStyleを作成しておくと便利かもしれません。

struct LargeProgressBarStyle: ProgressViewStyle {

  func makeBody(configuration: Configuration) -> some View {
      ProgressView(configuration)
          .frame(height: 40)
          .scaleEffect(x: 1, y: 40, anchor: .center)
          .clipShape(Capsule())
  }
}
struct ProgressBarTestView: View {
    var body: some View {
        ProgressView(value: 20, total: 100)
            .tint(.red)
            .progressViewStyle(LargeProgressBarStyle())
            .padding()
    }
}

おわりに

これで大きいプログレスバーを表示できるようになりました!
簡単に大きいサイズにできなくしているApple側の意図が気になるところです🤔
「もっと簡単に大きくできるよ」などの情報ありましたら教えていただけると嬉しいです☺︎

参考

https://stackoverflow.com/questions/64936411/change-size-height-of-progressview-in-swiftui

この記事をシェアする

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.